package com.xyauto.Dialog;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.media.AudioManager;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;

import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.xyauto.adapter.DragAdapter;
import com.xyauto.adapter.ViewPagerAdapter;
import com.xyauto.floatmenu.floatmenu.customfloat.BaseFloatDailog;

import com.xyauto.helper.ItemDragHelperCallback;
import com.xyauto.qiehuan.BlankFragment;

import com.xyauto.qiehuan.Module;
import com.xyauto.xfq.R;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;


import androidx.fragment.app.Fragment;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;


/**
 * Created by lts on 2022/9/13.
 */

public class MyFloatDialog extends BaseFloatDailog implements View.OnClickListener {

    private static final String APP_DEFAULT_PACKGAE = "com.acloud.stub.localmusic";
    private static final String APP_DEFAULT_SERVICE_CLASS1 = "com.acloud.stub.service.XYPlayerService";

    private ViewPager viewPager;
    private LinearLayout llChat, llContacts, llFind, llProfile;
    private ImageView ivChat, ivContacts, ivFind, ivProfile, ivCurrent;
    private View view1, view2, view3, view4;

    private ImageView speedlogo;
    private TextView speedtext;
    private TextView music_title, tv_music_title, tv_music_icon_album, tv_music_icon_artist;
    private Button btn_music_prev, btn_music_play, btn_music_next;

    private List<Module> items;
    private boolean isplay = false;
    private RecyclerView mRecy;
    private Boolean mRecyFlag=false;
    private ImageView ic_recy_settings,ic_settings;
    private TextView text_recy_settings;
    private SeekBar volumeSeekBar, brightnessSeekBar;
    private TextView volumetext, brightnesstext;
    private DragAdapter mApterRecyad;
    private WifiManager wifiManager;
    private BluetoothAdapter bluetoothAdapter;
    private AudioManager mAudioManager;

    private int mCurrentVolume = 0;//当前声音
    private int mMaxVolume; // 最大声音 */

    public MyFloatDialog(Context context) {
        super(context);

        IntentFilter filter = new IntentFilter();
        filter.addAction("com.gps.broadcasereceiver.MYRECEIVER");
        filter.addAction("xy.xygala.lamplet");


        filter.addAction("update.widget.songname");
        filter.addAction("update.widget.playbtnstate");

        getContext().registerReceiver(receiver, filter);

    }

    @Override
    protected View getLeftView(LayoutInflater inflater, View.OnClickListener onClickListener) {
        if (getContext() != null) {
            Toast.makeText(getContext(), "getLeftView", Toast.LENGTH_SHORT).show();
        }
        View view = inflater.inflate(R.layout.layout_menu_left, null);
        ImageView leftLogo = (ImageView) view.findViewById(R.id.leftlogo);
        leftLogo.setOnClickListener(onClickListener);
        return view;
    }

    @Override
    protected View getRightView(LayoutInflater inflater, View.OnClickListener onClickListener) {
        View view = inflater.inflate(R.layout.layout_menu_right, null);
        ImageView rightLogo = (ImageView) view.findViewById(R.id.rightlogo);
        rightLogo.setOnClickListener(onClickListener);
        initPager(view, inflater);
        initTabView(view);

        return view;
    }

    @Override
    protected View getBottomView(LayoutInflater inflater, View.OnClickListener onClickListener) {
        if (getContext() != null) {
            Toast.makeText(getContext(), "getBottomView", Toast.LENGTH_SHORT).show();
        }
        View view = inflater.inflate(R.layout.layout_menu_bottom, null);
        ImageView leftLogo = (ImageView) view.findViewById(R.id.bottomlogo);
        leftLogo.setOnClickListener(onClickListener);

        bottominit(view);
        registerContentObserver("volume_music", new ContentObserver(new Handler()) {
            @Override
            public void onChange(boolean selfChange) {
                super.onChange(selfChange);
                Log.e(TAG, "onChange: --");
                if (isopenMenu() && mAudioManager != null) {
                    mCurrentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                    volumeSeekBar.setProgress(mCurrentVolume);
                    int currentBrightness = Settings.System.getInt(getContext().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, -1);
                    brightnessSeekBar.setMax(255);
                    if (currentBrightness != -1) {
                        brightnesstext.setText(currentBrightness * 100 / 255 + "");
                        brightnessSeekBar.setProgress(currentBrightness);
                    }
                }
            }
        });
        return view;
    }

    @Override
    protected View getLogoView(LayoutInflater inflater) {

        View view = inflater.inflate(R.layout.layout_menu_logo, null);

        view.setTag(view.findViewById(R.id.logo));
        return view;
    }

    @Override
    protected int getLogoRes(int mLocation) {
        switch (mLocation) {
            case LEFT:
                return R.drawable.logo_show_img_left;
            case RIGHT:
                return R.drawable.logo_show_img_right;
            case BOTTOM:
                return R.drawable.logo_show_img_bottom;
        }
        return 0;
    }

    @Override
    protected void resetLogoViewSize(int hintLocation, View logoView) {
        Log.e(TAG, "resetLogoViewSize: ");
        logoView.clearAnimation();
        logoView.setTranslationX(0);
        logoView.setTranslationY(0);
        logoView.setScaleX(1);
        logoView.setScaleY(1);
    }

    @Override
    protected void dragingLogoViewOffset(View logoView, boolean isDraging, boolean isResetPosition, float offset) {
        if (isDraging && offset > 0) {
            //logoView.setBackgroundDrawable(null);
            logoView.setBackgroundResource(R.drawable.yw_game_logo);
            ((ImageView) (logoView.getTag())).setVisibility(View.INVISIBLE);
            /*logoView.setScaleX(1 + offset);
            logoView.setScaleY(1 + offset);*/
        } else {
            logoView.setBackgroundResource(R.drawable.yw_game_float_menu_bg);
            ((ImageView) (logoView.getTag())).setVisibility(View.VISIBLE);
            logoView.setTranslationX(0);
            logoView.setTranslationY(0);
            logoView.setScaleX(1);
            logoView.setScaleY(1);
        }


        if (isResetPosition) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                // logoView.setRotation(offset * 360);
            }
        } else {
            //   logoView.setRotation(offset * 360);
        }
    }

    @Override
    public void shrinkLeftLogoView(View smallView) {
        Log.d(TAG, "shrinkLeftLogoView: ");
        smallView.setTranslationX(-smallView.getWidth() / 3);
    }

    @Override
    public void shrinkRightLogoView(View smallView) {
        Log.d(TAG, "shrinkRightLogoView: ");
        smallView.setTranslationX(smallView.getWidth() / 3);
    }

    @Override
    public void shrinkBottomLogoView(View smallView) {
        Log.d("TAG", "shrinkBottomLogoView: ");
        smallView.setTranslationY(smallView.getHeight() / 3);
    }

    @Override
    public void leftViewOpened(View leftView) {
        //   leftView.setVisibility(View.VISIBLE);
        Toast.makeText(getContext(), "左边的菜单被打开了", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void rightViewOpened(View rightView) {
        // rightView.setVisibility(View.VISIBLE);
        Toast.makeText(getContext(), "右边的菜单被打开了", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void bottomViewOpened(View rightView) {
        //   rightView.setVisibility(View.VISIBLE);
        items = mApterRecyad.getItem();
        for (int i = 0; i < items.size(); i++) {
            bottomswitchinit(i);
        }
        mApterRecyad.notifyDataSetChanged();
        Toast.makeText(getContext(), "底部的菜单被打开了", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void floatViewClosed(View smallView) {
        // smallView.setVisibility(View.GONE);
        Toast.makeText(getContext(), "菜单被关闭了", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestoryed() {
        if (isApplictionDialog()) {
            if (getContext() instanceof Activity) {
                dismiss();
            }
        }
    }


    private void bottominit(View view) {
        if (getContext() == null) {
            Log.e(TAG, "init: DragAdapter error");
            return;
        }
        mRecy = (RecyclerView) view.findViewById(R.id.recy);
        volumeSeekBar = (SeekBar) view.findViewById(R.id.volume);
        brightnessSeekBar = (SeekBar) view.findViewById(R.id.brightness);
        volumetext = (TextView) view.findViewById(R.id.volumetext);
        brightnesstext = (TextView) view.findViewById(R.id.brightnesstext);
        ic_recy_settings= (ImageView) view.findViewById(R.id.ic_recy_settings);
        ic_settings= (ImageView) view.findViewById(R.id.ic_settings);
        text_recy_settings = (TextView) view.findViewById(R.id.text_recy_settings);

        wifiManager = (WifiManager) getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);

        items = Module.getModuleList();


        GridLayoutManager manager = new GridLayoutManager(getContext(), 5);
        mRecy.setLayoutManager(manager);

        ItemDragHelperCallback callback = new ItemDragHelperCallback() {
            @Override
            public boolean isLongPressDragEnabled() {
                // 长按拖拽打开
                return mRecyFlag;
            }
        };

        ItemTouchHelper helper = new ItemTouchHelper(callback);
        helper.attachToRecyclerView(mRecy);

        mApterRecyad = new DragAdapter(getContext(), items);
        mRecy.setAdapter(mApterRecyad);

        mApterRecyad.setOnMyChannelItemClickListener(new DragAdapter.OnMyChannelItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                Log.e(TAG, "onItemClick: position" + position);
               // Toast.makeText(getContext(),"onItemClick"+ mApterRecyad.getItem().get(position).getmName_id(), Toast.LENGTH_SHORT).show();
               if (!mRecyFlag){
                   bottomswitch(v, position);
               }
            }
        });
        mApterRecyad.setOnMyChannelItemLongClickListener(new DragAdapter.OnMyChannelItemLongClickListener() {
            @Override
            public Boolean onItemLongClick(View v, int position) {
                if(!mRecyFlag){
                    switch (mApterRecyad.getItem().get(position).getmName_id()){
                        case R.string.status_bluetooth:
                            Log.e("TAG", "onLongClick: status_bluetooth" );
                            Intent intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
                            getContext().startActivity(intent);
                            return true;
                        case R.string.status_wifi:
                            Log.e("TAG", "onLongClick: status_wifi" );
                            Intent intent2 = new Intent(Settings.ACTION_WIFI_SETTINGS);
                            getContext().startActivity(intent2);
                            return true;
                    }
                }
                return false;
            }
        });

        mMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        mCurrentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        volumeSeekBar.setMax(mMaxVolume);
        volumeSeekBar.setProgress(mCurrentVolume);
        volumetext.setText(mCurrentVolume + "");
        volumeSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                volumetext.setText(progress + "");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 可选实现
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 可选实现
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, seekBar.getProgress(), 0);
            }
        });

        ContentResolver contentResolver = getContext().getContentResolver();
        int currentBrightness = Settings.System.getInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, -1);
        brightnessSeekBar.setMax(255);
        if (currentBrightness != -1) {
            brightnesstext.setText(currentBrightness * 100 / 255 + "");
            brightnessSeekBar.setProgress(currentBrightness);
            Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
        }
        brightnessSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS, progress);
                Log.e(TAG, "onProgressChanged: " + progress * 255 / 100);
                brightnesstext.setText(progress * 100 / 255 + "");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 可选实现
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 可选实现
            }
        });

        ic_recy_settings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mRecyFlag){
                    v.setSelected(false);
                    text_recy_settings.setVisibility(View.GONE);
                    mRecyFlag=false;
                }else {
                    v.setSelected(true);
                    text_recy_settings.setVisibility(View.VISIBLE);
                    mRecyFlag=true;
                }

            }
        });
        ic_settings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                getContext().getApplicationContext().startActivity(intent);
            }
        });

    }

    public void registerContentObserver(String name, ContentObserver observer) {
        //Settings.System.CONTENT_URI   //Settings.System.getUriFor(name)
        Log.e(TAG, "registerContentObserver: " + name);
        getContext().getContentResolver()
                .registerContentObserver(Settings.System.CONTENT_URI, true, observer);
    }

    private void bottomswitchinit(int position) {

        switch (items.get(position).getmName_id()) {
            case R.string.status_wifi:
                if (wifiManager.isWifiEnabled()) {
                    items.get(position).setSelect(true);
                } else {
                    items.get(position).setSelect(false);
                }
                break;
            case R.string.status_bluetooth:
                if (bluetoothAdapter == null) {
                    // 设备不支持蓝牙
                    Toast.makeText(getContext().getApplicationContext(), "设备不支持蓝牙", Toast.LENGTH_SHORT).show();
                } else if (!bluetoothAdapter.isEnabled()) {
                    // 蓝牙未启用
                    // 这里可以提示用户开启蓝牙，或者直接调用 openBluetooth() 方法
                    items.get(position).setSelect(false);
                } else {
                    // 蓝牙已启用
                    // 可以进行蓝牙相关的操作
                    items.get(position).setSelect(true);
                }
                break;
            case R.string.status_hotspot:
                try {
                    Method method = wifiManager.getClass().getMethod("getWifiApState");
                    int state = (Integer) method.invoke(wifiManager);
                    switch (state) {
                        case 13:
                            // 热点已开启
                            items.get(position).setSelect(true);
                            break;
                        case 11:
                            // 热点已关闭
                            items.get(position).setSelect(false);
                            break;
                        // 其他状态...
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    // 处理反射调用失败的情况
                }
                break;
            case R.string.status_screenshot:
                break;
            case R.string.status_carAmplifier:
                int ampsts = android.provider.Settings.System.getInt(getContext().getContentResolver(), "Amp_Power", 0);
                if (0 != ampsts)
                    items.get(position).setSelect(false);
                else
                    items.get(position).setSelect(true);
                break;

            case R.string.status_Offscreen:
                break;
            case R.string.status_car_Setting:
                break;
            case R.string.status_clean_up:
                break;
            case R.string.status_optlcal:
                int optical = android.provider.Settings.System.getInt(getContext().getContentResolver(), "OPTICAL", 0);
                if (0 != optical)
                    items.get(position).setSelect(false);
                else
                    items.get(position).setSelect(true);
                break;
            case R.string.status_recent:
                break;
        }

    }

    private void bottomswitch(View v, int position) {

        items = mApterRecyad.getItem();
        switch (items.get(position).getmName_id()) {
            case R.string.status_wifi:
                if (!wifiManager.isWifiEnabled()) {
                    wifiManager.setWifiEnabled(true);
                    v.setSelected(true);
                } else {
                    wifiManager.setWifiEnabled(false);
                    v.setSelected(false);
                }
                break;
            case R.string.status_bluetooth:
                if (bluetoothAdapter.isEnabled()) {
                    bluetoothAdapter.disable();
                    v.setSelected(false);
                } else {
                    if (bluetoothAdapter.enable()) {
                        v.setSelected(true);
                    } else {
                        v.setSelected(false);
                    }

                }
                break;
            case R.string.status_hotspot:
                try {
                    Method method = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
                    WifiConfiguration config = new WifiConfiguration();
                    config.SSID = "\"MyHotspot\""; // 引号必须包含在内
                    config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
                    config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

                    boolean enable;
                    if (v.isSelected()) {
                        // 关闭热点
                        enable = (Boolean) method.invoke(wifiManager, null, false);
                        if (!enable) {
                            // 热点已关闭
                            v.setSelected(false);
                        }
                    } else {
                        // 打开热点
                        enable = (Boolean) method.invoke(wifiManager, config, true);
                        if (enable) {
                            // 热点已打开
                            v.setSelected(true);
                        } else {
                            v.setSelected(false);
                        }
                    }

                } catch (Exception e) {
                    Intent intent = new Intent(Settings.ACTION_WIFI_IP_SETTINGS);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    getContext().getApplicationContext().startActivity(intent);
                    e.printStackTrace();
                }
                break;
            case R.string.status_screenshot:
                openMenu();
                getContext().sendBroadcast(new Intent("xy.capture.screenshortcut"));
                break;
            case R.string.status_carAmplifier:
                Amp_PowerSet();
                int ampsts = android.provider.Settings.System.getInt(getContext().getContentResolver(), "Amp_Power", 0);
                if (0 != ampsts)
                    v.setSelected(false);
                else
                    v.setSelected(true);

                break;

            case R.string.status_Offscreen:
                android.provider.Settings.System.putInt(getContext().getContentResolver(), "xy_light_level", 2);
                getContext().sendBroadcast(new Intent("xy.android.lightscreen").putExtra("cur_light_level", 2));
                break;
            case R.string.status_car_Setting:
                Intent setintent = new Intent();
                setintent.setComponent(new ComponentName("com.xyauto.Settings", "com.xyauto.Settings.MainActivity"));
                setintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                getContext().getApplicationContext().startActivity(setintent);
                break;
            case R.string.status_clean_up:
                getContext().sendBroadcast(new Intent("xy.onekeyclean"));
                break;
            case R.string.status_optlcal:
                OpticalSet();
                int optical = android.provider.Settings.System.getInt(getContext().getContentResolver(), "OPTICAL", 0);
                if (0 != optical)
                    v.setSelected(false);
                else
                    v.setSelected(true);
                break;
            case R.string.status_recent:
                break;
        }

    }

    private void Amp_PowerSet() {
        int ampsts = android.provider.Settings.System.getInt(getContext().getContentResolver(), "Amp_Power", 0);
        Intent intent = new Intent("action.ampctrl.set");

        if (ampsts == 0) {
            ampsts = 1;

        } else if (ampsts == 1) {
            ampsts = 0;

        }
        android.provider.Settings.System.putInt(getContext().getContentResolver(), "Amp_Power", ampsts);

        intent.putExtra("amp_ctrl", ampsts);
        getContext().sendBroadcast(intent);
    }

    private void OpticalSet() {
        int optical = android.provider.Settings.System.getInt(getContext().getContentResolver(), "OPTICAL", 0);
        Intent intent = new Intent("action.optical.set");

        if (optical == 0) {
            optical = 1;
        } else if (optical == 1) {
            optical = 0;
        }
        android.provider.Settings.System.putInt(getContext().getContentResolver(), "OPTICAL", optical);

        intent.putExtra("optical", optical);
        getContext().sendBroadcast(intent);
    }

    private void initTabView(View view) {
        llChat = view.findViewById(R.id.id_tab_weixin);
        llChat.setOnClickListener(this);
        llContacts = view.findViewById(R.id.id_tab_contact);
        llContacts.setOnClickListener(this);
        llFind = view.findViewById(R.id.id_tab_find);
        llFind.setOnClickListener(this);
        llProfile = view.findViewById(R.id.id_tab_profile);
        llProfile.setOnClickListener(this);
        ivChat = view.findViewById(R.id.tab_iv_weixin);
        ivContacts = view.findViewById(R.id.tab_iv_contact);
        ivFind = view.findViewById(R.id.tab_iv_find);
        ivProfile = view.findViewById(R.id.tab_iv_profile);

        ivChat.setSelected(true);
        ivCurrent = ivChat;

    }

    private void initPager(View view, LayoutInflater inflater) {
        viewPager = view.findViewById(R.id.id_viewpager);
        ArrayList<Fragment> fragments = new ArrayList<>();
        fragments.add(BlankFragment.newInstance("闹钟"));
        fragments.add(BlankFragment.newInstance("车速"));
        fragments.add(BlankFragment.newInstance("车标"));
        fragments.add(BlankFragment.newInstance("音乐"));


        view1 = inflater.inflate(R.layout.layout1, null);
        view2 = inflater.inflate(R.layout.layout2, null);
        view3 = inflater.inflate(R.layout.layout3, null);
        view4 = inflater.inflate(R.layout.layout4, null);

        List<View> viewList = new ArrayList<>();
        viewList.add(view1);
        viewList.add(view2);
        viewList.add(view3);
        viewList.add(view4);
        ViewPagerAdapter myAdapter = new ViewPagerAdapter(viewList);

        viewPager.setAdapter(myAdapter);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                Log.e("position--", "position:" + position);
                changeTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


        speedlogo = view2.findViewById(R.id.speedlogo);
        speedtext = view2.findViewById(R.id.speedtext);

        music_title = view4.findViewById(R.id.music_title);
        music_title = view4.findViewById(R.id.music_title);
        tv_music_title = view4.findViewById(R.id.tv_music_title);
        tv_music_icon_album = view4.findViewById(R.id.tv_music_icon_album);
        tv_music_icon_artist = view4.findViewById(R.id.tv_music_icon_artist);
        btn_music_prev = view4.findViewById(R.id.btn_music_prev);
        btn_music_prev.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getIntent("xy.cdwidget.prev");
                // getContext().sendBroadcast(intent);
            }
        });
        btn_music_play = view4.findViewById(R.id.btn_music_play);
        btn_music_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isplay) {
                    getIntent("xy.cdwidget.pause");
                    btn_music_play.setBackgroundResource(R.drawable.bt_music_play);
                    isplay = false;
                } else {
                    getIntent("xy.cdwidget.play");
                    btn_music_play.setBackgroundResource(R.drawable.bt_music_pause);
                    isplay = true;
                }
                //  getContext().sendBroadcast(intent);

            }
        });
        btn_music_next = view4.findViewById(R.id.btn_music_next);
        btn_music_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getIntent("xy.cdwidget.next");
                //  getContext().sendBroadcast(intent);
            }
        });


    }

    private void changeTab(int position) {
        ivCurrent.setSelected(false);
        switch (position) {
            case R.id.id_tab_weixin:
                viewPager.setCurrentItem(0);
            case 0:
                ivChat.setSelected(true);
                ivCurrent = ivChat;
                break;
            case R.id.id_tab_contact:
                viewPager.setCurrentItem(1);
            case 1:
                ivContacts.setSelected(true);
                ivCurrent = ivContacts;
                break;
            case R.id.id_tab_find:
                viewPager.setCurrentItem(2);
            case 2:
                ivFind.setSelected(true);
                ivCurrent = ivFind;
                break;
            case R.id.id_tab_profile:
                viewPager.setCurrentItem(3);
            case 3:
                ivProfile.setSelected(true);
                ivCurrent = ivProfile;
                break;

        }
    }

    @Override
    public void onClick(View view) {
        changeTab(view.getId());
    }

    private void getIntent(String action) {
        if (getContext() != null) {
            try {
        		/*ComponentName component = new ComponentName(APP_DEFAULT_PACKGAE, APP_DEFAULT_SERVICE_CLASS);
	            Intent intent = new Intent();
	            intent.setComponent(component);
	            intent.setAction(action);
	            this.getContext().startService(intent);*/

                ComponentName component1 = new ComponentName(APP_DEFAULT_PACKGAE, APP_DEFAULT_SERVICE_CLASS1);
                Intent intent1 = new Intent();
                intent1.setComponent(component1);
                intent1.setAction(action);
                //this.getContext().startService(intent1);
                //app api����26����ǰ̨������С��26ֱ�������
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    getContext().startForegroundService(intent1);
                } else
                    getContext().startService(intent1);
            } catch (Exception e) {
                Log.i("Qt5Core", "startService Exception:");
            }
        }
    }


    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("TAG", intent.getAction() + "广播");
            String action = intent.getAction();
            if (action.equals("com.gps.broadcasereceiver.MYRECEIVER")) {
                speedtext.setText(intent.getIntExtra("GPS_CURRENT_SPEED", 0) + "km/h");
                Log.e("TAG", intent.getIntExtra("GPS_CURRENT_SPEED", 0) + "车速");
            } else if (action.equals("xy.xygala.lamplet")) {
                int flag = intent.getIntExtra("lamplet_state", 0);//0关灯,1开灯
                if (flag == 0) {
                    speedlogo.setBackgroundResource(R.drawable.che_guandeng);
                } else {

                    speedlogo.setBackgroundResource(R.drawable.che_kaideng);
                }

            } else if (action.equals("update.widget.playbtnstate")) {

                isplay = intent.getBooleanExtra("PlayState", false);
                if (!isplay) {
                    btn_music_play.setBackgroundResource(R.drawable.bt_music_play);
                } else {
                    btn_music_play.setBackgroundResource(R.drawable.bt_music_pause);
                }


                // Log.e("TAG",intent.getBooleanExtra("PlayState", false)+"--isplay ");
            } else if (intent.getAction().equals("update.widget.songname")) {

                String Cursname = intent.getStringExtra("curplaysong");
                music_title.setText(Cursname);
                tv_music_title.setText(Cursname);
                if (Cursname.indexOf('-') > 0) {
                    tv_music_icon_album.setText(Cursname.substring(Cursname.indexOf('-') + 1));
                    tv_music_icon_artist.setText(Cursname.substring(0, Cursname.indexOf('-')));
                } else {
                    tv_music_icon_album.setText(Cursname);
                    tv_music_icon_artist.setText(Cursname);
                }
                isplay = intent.getBooleanExtra("PlayState", false);
                if (!isplay) {
                    btn_music_play.setBackgroundResource(R.drawable.bt_music_play);

                } else {
                    btn_music_play.setBackgroundResource(R.drawable.bt_music_pause);
                }
                //  Log.e("TAG",Cursname+"--Cursname--"+intent.getBooleanExtra("PlayState", false)+"--isplay--");

                String artistPicPath = "";
                if (intent.hasExtra("artistPicPath")) {
                    artistPicPath = intent.getStringExtra("artistPicPath");
                    Log.e("TAG", artistPicPath + "--artistPicPath--");
                }

            }
        }
    };

}
